<html><head><meta charset="utf-8"><title>35 经验总结：各种锁在工作中使用场景和细节    -慕课专栏</title>
			<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
			<meta name="renderer" content="webkit">
			<meta property="qc:admins" content="77103107776157736375">
			<meta property="wb:webmaster" content="c4f857219bfae3cb">
			<meta http-equiv="Access-Control-Allow-Origin" content="*">
			<meta http-equiv="Cache-Control" content="no-transform ">
			<meta http-equiv="Cache-Control" content="no-siteapp">
			<link rel="apple-touch-icon" sizes="76x76" href="https://www.imooc.com/static/img/common/touch-icon-ipad.png">
			<link rel="apple-touch-icon" sizes="120x120" href="https://www.imooc.com/static/img/common/touch-icon-iphone-retina.png">
			<link rel="apple-touch-icon" sizes="152x152" href="https://www.imooc.com/static/img/common/touch-icon-ipad-retina.png">
			<link href="https://moco.imooc.com/captcha/style/captcha.min.css" rel="stylesheet">
			<link rel="stylesheet" href="https://www.imooc.com/static/moco/v1.0/dist/css/moco.min.css?t=201907021539" type="text/css">
			<link rel="stylesheet" href="https://www.imooc.com/static/lib/swiper/swiper-3.4.2.min.css?t=201907021539">
			<link rel="stylesheet" href="https://static.mukewang.com/static/css/??base.css,common/common-less.css?t=2.5,column/zhuanlanChapter-less.css?t=2.5,course/inc/course_tipoff-less.css?t=2.5?v=201907051055" type="text/css">
			<link charset="utf-8" rel="stylesheet" href="https://www.imooc.com/static/lib/ueditor/themes/imooc/css/ueditor.css?v=201907021539"><link rel="stylesheet" href="https://www.imooc.com/static/lib/baiduShare/api/css/share_style0_16.css?v=6aba13f0.css"></head>
			<body><div id="main">


<div class="main-con hide-menu">
    <!-- 左侧菜单 & 索引 -->
    
    <div class="right-content" style="padding-left: 0px;">
        <div class="container clearfix" id="top" style="width: 1134px; display: block;">
            
            
            <div class="center_con js-center_con l" style="width: 1134px;">
                <div class="article-con">
                                            <!-- 买过的阅读 -->
                        

                    
                    <div class="art-title" style="margin-top: 0px;">
                        35 经验总结：各种锁在工作中使用场景和细节    
                    </div>
                    <div class="art-info clearfix">
                        
                        <span class="l">
                            更新时间：2019-11-14 11:04:28
                        </span>
                    </div>
                    <div class="art-top">
                                                <img src="https://img1.mukewang.com/5dccbd060001aa0f06400359.jpg" alt="">
                                                                        <div class="famous-word-box">
                            <img src="https://www.imooc.com/static/img/column/bg-l.png" alt="" class="bg1 bg">
                            <img src="https://www.imooc.com/static/img/column/bg-r.png" alt="" class="bg2 bg">
                            <div class="famous-word">富贵必从勤苦得。<p class="author">——杜甫</p></div>
                        </div>
                                            </div>
                    <div class="art-content js-lookimg">
                        <div id="article_content">
                            <div class="cl-preview-section"><h2 id="引导语" style="font-size: 30px;">引导语</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">本章主要说一说锁在工作中的使用场景，主要以 synchronized 和 CountDownLatch 为例，会分别描述一下这两种锁的使用场景和姿势。</p>
</div><div class="cl-preview-section"><h2 id="synchronized" style="font-size: 30px;">1 synchronized</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">synchronized 是可重入的排它锁，和 ReentrantLock 锁功能相似，任何使用 synchronized 的地方，几乎都可以使用 ReentrantLock 来代替，两者最大的相似点就是：可重入 + 排它锁，两者的区别主要有这些：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">ReentrantLock 的功能更加丰富，比如提供了 Condition，可以打断的加锁 API、能满足锁 + 队列的复杂场景等等；</li>
<li style="font-size: 20px; line-height: 38px;">ReentrantLock 有公平锁和非公平锁之分，而 synchronized 都是非公平锁；</li>
<li style="font-size: 20px; line-height: 38px;">两者的使用姿势也不同，ReentrantLock 需要申明，有加锁和释放锁的 API，而 synchronized 会自动对代码块进行加锁释放锁的操作，synchronized 使用起来更加方便。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">synchronized 和 ReentrantLock 功能相近，所以我们就以 synchronized 举例。</p>
</div><div class="cl-preview-section"><h3 id="共享资源初始化">1.1 共享资源初始化</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在分布式的系统中，我们喜欢把一些死的配置资源在项目启动的时候加锁到 JVM 内存里面去，这样请求在拿这些共享配置资源时，就可直接从内存里面拿，不必每次都从数据库中拿，减少了时间开销。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">一般这样的共享资源有：死的业务流程配置 + 死的业务规则配置。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">共享资源初始化的步骤一般为：项目启动 -&gt; 触发初始化动作 -&gt;单线程从数据库中捞取数据 -&gt; 组装成我们需要的数据结构 -&gt; 放到 JVM 内存中。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在项目启动时，为了防止共享资源被多次加载，我们往往会加上排它锁，让一个线程加载共享资源完成之后，另外一个线程才能继续加载，此时的排它锁我们可以选择 synchronized 或者 ReentrantLock，我们以 synchronized 为例，写了 mock 的代码，如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java">  <span class="token comment">// 共享资源</span>
  <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> Map<span class="token operator">&lt;</span>String<span class="token punctuation">,</span> String<span class="token operator">&gt;</span> SHARED_MAP <span class="token operator">=</span> Maps<span class="token punctuation">.</span><span class="token function">newConcurrentMap</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// 有无初始化完成的标志位</span>
  <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">boolean</span> loaded <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>

  <span class="token comment">/**
   * 初始化共享资源
   */</span>
  <span class="token annotation punctuation">@PostConstruct</span>
  <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">init</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>loaded<span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token keyword">return</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">synchronized</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token comment">// 再次 check</span>
      <span class="token keyword">if</span><span class="token punctuation">(</span>loaded<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"SynchronizedDemo init begin"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token comment">// 从数据库中捞取数据，组装成 SHARED_MAP 的数据格式</span>
      loaded <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"SynchronizedDemo init end"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">不知道大家有没有从上述代码中发现 @PostConstruct 注解，@PostConstruct 注解的作用是在 Spring 容器初始化时，再执行该注解打上的方法，也就是说上图说的 init 方法触发的时机，是在 Spring 容器启动的时候。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">大家可以下载演示代码，找到 DemoApplication 启动文件，在 DemoApplication 文件上右击 run，就可以启动整个 Spring Boot 项目，在 init 方法上打上断点就可以调试了。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们在代码中使用了 synchronized 来保证同一时刻，只有一个线程可以执行初始化共享资源的操作，并且我们加了一个共享资源加载完成的标识位（loaded），来判断是否加载完成了，如果加载完成，那么其它加载线程直接返回。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">如果把 synchronized 换成 ReentrantLock 也是一样的实现，只不过需要显示的使用 ReentrantLock 的 API 进行加锁和释放锁，使用 ReentrantLock 有一点需要注意的是，我们需要在 try 方法块中加锁，在 finally 方法块中释放锁，这样保证即使 try 中加锁后发生异常，在 finally 中也可以正确的释放锁。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">有的同学可能会问，不是可以直接使用了 ConcurrentHashMap 么，为什么还需要加锁呢？的确 ConcurrentHashMap 是线程安全的，但它只能够保证 Map 内部数据操作时的线程安全，是无法保证多线程情况下，查询数据库并组装数据的整个动作只执行一次的，我们加 synchronized 锁住的是整个操作，保证整个操作只执行一次。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">完整 demo 见 SynchronizedDemo。</p>
</div><div class="cl-preview-section"><h2 id="countdownlatch" style="font-size: 30px;">2 CountDownLatch</h2>
</div><div class="cl-preview-section"><h3 id="场景">2.1 场景</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">1：小明在淘宝上买了一个商品，觉得不好，把这个商品退掉(商品还没有发货，只退钱)，我们叫做单商品退款，单商品退款在后台系统中运行时，整体耗时 30 毫秒。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">2：双 11，小明在淘宝上买了 40 个商品，生成了同一个订单（实际可能会生成多个订单，为了方便描述，我们说成一个），第二天小明发现其中 30 个商品是自己冲动消费的，需要把 30 个商品一起退掉。</p>
</div><div class="cl-preview-section"><h3 id="实现">2.2 实现</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">此时后台只有单商品退款的功能，没有批量商品退款的功能（30 个商品一次退我们称为批量），为了快速实现这个功能，同学 A 按照这样的方案做的：for 循环调用 30 次单商品退款的接口，在 qa 环境测试的时候发现，如果要退款 30 个商品的话，需要耗时：30 * 30 = 900 毫秒，再加上其它的逻辑，退款 30 个商品差不多需要 1 秒了，这个耗时其实算很久了，当时同学 A 提出了这个问题，希望大家帮忙看看如何优化整个场景的耗时。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">同学 B 当时就提出，你可以使用线程池进行执行呀，把任务都提交到线程池里面去，假如机器的 CPU 是 4 核的，最多同时能有 4 个单商品退款可以同时执行，同学 A 觉得很有道理，于是准备修改方案，为了便于理解，我们把两个方案都画出来，对比一下：<br>
<img class="" src="https://img.mukewang.com/5dc386970001fb8b12120716.png" data-original="//img.mukewang.com/5dc386970001fb8b12120716.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">同学 A 于是就按照演变的方案去写代码了，过了一天，抛出了一个问题：向线程池提交了 30 个任务后，主线程如何等待 30 个任务都执行完成呢？因为主线程需要收集 30 个子任务的执行情况，并汇总返回给前端。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">大家可以先不往下看，自己先思考一下，我们前几章说的那种锁可以帮助解决这个问题？</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">CountDownLatch 可以的，CountDownLatch 具有这种功能，让主线程去等待子任务全部执行完成之后才继续执行。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">此时还有一个关键，我们需要知道子线程执行的结果，所以我们用 Runnable 作为线程任务就不行了，因为 Runnable 是没有返回值的，我们需要选择 Callable 作为任务。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们写了一个 demo，首先我们来看一下单个商品退款的代码：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token comment">// 单商品退款，耗时 30 毫秒，退款成功返回 true，失败返回 false</span>
<span class="token annotation punctuation">@Slf4j</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">RefundDemo</span> <span class="token punctuation">{</span>

  <span class="token comment">/**
   * 根据商品 ID 进行退款
   * @param itemId
   * @return
   */</span>
  <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">refundByItem</span><span class="token punctuation">(</span>Long itemId<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">try</span> <span class="token punctuation">{</span>
      <span class="token comment">// 线程沉睡 30 毫秒，模拟单个商品退款过程</span>
      Thread<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">30</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"refund success,itemId is {}"</span><span class="token punctuation">,</span> itemId<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"refundByItemError,itemId is {}"</span><span class="token punctuation">,</span> itemId<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">接着我们看下 30 个商品的批量退款，代码如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token annotation punctuation">@Slf4j</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">BatchRefundDemo</span> <span class="token punctuation">{</span>
	<span class="token comment">// 定义线程池</span>
  <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">final</span> ExecutorService EXECUTOR_SERVICE <span class="token operator">=</span>
      <span class="token keyword">new</span> <span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> 0L<span class="token punctuation">,</span>
                                TimeUnit<span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span>
                                <span class="token keyword">new</span> <span class="token class-name">LinkedBlockingQueue</span><span class="token operator">&lt;</span><span class="token operator">&gt;</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token annotation punctuation">@Test</span>
  <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">batchRefund</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> InterruptedException <span class="token punctuation">{</span>
    <span class="token comment">// state 初始化为 30 </span>
    CountDownLatch countDownLatch <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">CountDownLatch</span><span class="token punctuation">(</span><span class="token number">30</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    RefundDemo refundDemo <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RefundDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">// 准备 30 个商品</span>
    List<span class="token operator">&lt;</span>Long<span class="token operator">&gt;</span> items <span class="token operator">=</span> Lists<span class="token punctuation">.</span><span class="token function">newArrayListWithCapacity</span><span class="token punctuation">(</span><span class="token number">30</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">30</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      items<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>Long<span class="token punctuation">.</span><span class="token function">valueOf</span><span class="token punctuation">(</span>i<span class="token operator">+</span><span class="token string">""</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">// 准备开始批量退款</span>
    List<span class="token operator">&lt;</span>Future<span class="token operator">&gt;</span> futures <span class="token operator">=</span> Lists<span class="token punctuation">.</span><span class="token function">newArrayListWithCapacity</span><span class="token punctuation">(</span><span class="token number">30</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>Long item <span class="token operator">:</span> items<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 使用 Callable，因为我们需要等到返回值</span>
      Future<span class="token operator">&lt;</span>Boolean<span class="token operator">&gt;</span> future <span class="token operator">=</span> EXECUTOR_SERVICE<span class="token punctuation">.</span><span class="token function">submit</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Callable</span><span class="token operator">&lt;</span>Boolean<span class="token operator">&gt;</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> Boolean <span class="token function">call</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
          <span class="token keyword">boolean</span> result <span class="token operator">=</span> refundDemo<span class="token punctuation">.</span><span class="token function">refundByItem</span><span class="token punctuation">(</span>item<span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token comment">// 每个子线程都会执行 countDown，使 state -1 ，但只有最后一个才能真的唤醒主线程</span>
          countDownLatch<span class="token punctuation">.</span><span class="token function">countDown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token keyword">return</span> result<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
      <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token comment">// 收集批量退款的结果</span>
      futures<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>future<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"30 个商品已经在退款中"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 使主线程阻塞，一直等待 30 个商品都退款完成，才能继续执行</span>
    countDownLatch<span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"30 个商品已经退款完成"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 拿到所有结果进行分析</span>
    List<span class="token operator">&lt;</span>Boolean<span class="token operator">&gt;</span> result <span class="token operator">=</span> futures<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>fu<span class="token operator">-</span><span class="token operator">&gt;</span> <span class="token punctuation">{</span>
      <span class="token keyword">try</span> <span class="token punctuation">{</span>
        <span class="token comment">// get 的超时时间设置的是 1 毫秒，是为了说明此时所有的子线程都已经执行完成了</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span>Boolean<span class="token punctuation">)</span> fu<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span>TimeUnit<span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ExecutionException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">TimeoutException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span>Collectors<span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 打印结果统计</span>
    <span class="token keyword">long</span> success <span class="token operator">=</span> result<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>r<span class="token operator">-</span><span class="token operator">&gt;</span>r<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">count</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"执行结果成功{},失败{}"</span><span class="token punctuation">,</span>success<span class="token punctuation">,</span>result<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">-</span>success<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">上述代码只是大概的底层思路，真实的项目会在此思路之上加上请求分组，超时打断等等优化措施。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们来看一下执行的结果:<br>
<img class="" src="https://img.mukewang.com/5dc386a80001238109010819.png" data-original="//img.mukewang.com/5dc386a80001238109010819.png" alt="图片描述"></p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">从执行的截图中，我们可以明显的看到 CountDownLatch 已经发挥出了作用，主线程会一直等到 30 个商品的退款结果之后才会继续执行。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">接着我们做了一个不严谨的实验（把以上代码执行很多次，求耗时平均值），通过以上代码，30 个商品退款完成之后，整体耗时大概在 200 毫秒左右。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">而通过 for 循环单商品进行退款，大概耗时在 1 秒左右，前后性能相差 5 倍左右，for 循环退款的代码如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">long</span> begin1 <span class="token operator">=</span> System<span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span>Long item <span class="token operator">:</span> items<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  refundDemo<span class="token punctuation">.</span><span class="token function">refundByItem</span><span class="token punctuation">(</span>item<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"for 循环单个退款耗时{}"</span><span class="token punctuation">,</span>System<span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">-</span>begin1<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">性能的巨大提升是线程池 + 锁两者结合的功劳。</p>
</div><div class="cl-preview-section"><h2 id="总结" style="font-size: 30px;">3 总结</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">本章举了实际工作中的两个小案列，看到了 CountDownLatch 和 synchronized（ReentrantLock） 是如何结合实际需求进行落地的，特别是 CountDownLatch 的案列，使用线程池 + 锁结合的方式大大提高了生产效率，所以在工作中如果你也遇到相似的场景，可以毫不犹豫地用起来。</p>
</div>}
                        </div>
                    </div>
                                            <!-- 买过的阅读 -->
                        <div class="art-next-prev clearfix">
                                                                                                <!-- 已买且开放 或者可以试读 -->
                                    <a href="/read/47/article/876">
                                                                    <div class="prev l clearfix">
                                        <div class="icon l">
                                            <i class="imv2-arrow3_l"></i>
                                        </div>
                                        <p>
                                            34 只求问倒：连环相扣系列锁面试题 
                                        </p>
                                    </div>
                                </a>
                                                                                                                            <!-- 已买且开放 或者可以试读 -->
                                    <a href="/read/47/article/878">
                                                                    <div class="next r clearfix">
                                        <p>
                                            36 从容不迫：重写锁的设计结构和细节 
                                        </p>
                                        <div class="icon r">
                                            <i class="imv2-arrow3_r"></i>
                                        </div>

                                    </div>
                                </a>
                                                    </div>
                                    </div>
                <div class="comments-con js-comments-con" id="coments_con">
                </div>

                
            </div>
            
            
            

        </div>
    </div>
</div>

<div class="modal modal-jiaQun-new hide" id="modal-jiaQun">
    <div class="inner" style="">
        <div class="modal-close js-close-jiaQun">
            <i class="imv2-close"></i>
        </div>
        <div class="content">
            <img src="https://img2.mukewang.com/5d634d40000119e505400602.jpg">
            <div class="right-info">
                <div class="title">
                    扫码加入慕课Java核心用户群
                </div>
                <div class="desc">
                                            <p class="mb6">验证信息：<span id="joincode">1909271435058473</span><span class="copy js-copy-joincode">复制</span></p>
                                        <p class="mb6">QQ讨论群号：906691736</p>
                                            <p>QQ群URL：<a href="https://jq.qq.com/?_wv=1027&amp;k=55RtSbJ" target="_blank">点击访问</a></p>
                                    </div>
            </div>
            <p class="tip">若遇到搜索不到QQ群或加群失败，请联系客服邮箱:kf@imooc.com</p>
        </div>
    </div>
</div>
 
<!-- 专栏介绍页专栏评价 -->

<!-- 专栏介绍页底部三条评价 -->

<!-- 专栏阅读页弹层目录和介绍页页面目录 -->

<!-- 专栏阅读页发布回复 -->

<!-- 专栏阅读页发布评论 -->

<!-- 专栏阅读页底部评论 -->

<!-- 专栏阅读 单个 评论 -->

<!-- 新增回复和展开三条以外回复 -->

<!-- 立即订阅的弹窗 -->












</div></body></html>